package com.spark.tags;

import java.util.List;
import java.util.Map;

import com.spark.core.SparkBuilder;
import com.spark.core.SparkContext;
import com.spark.core.XMap;

public class GroupButton extends ViewComponent {
	
	public static final String TAG_NAME = "groupButton";
	public static final String PROPERTITY_BUTTONS = "buttons";
	public static final String PROPERTITY_ACTIVE_VALUE = "activeValue";
	
	private static final String DEFAULT_TEMPLATES = "switchButtons.ftl";
	private static final String DEFAULT_CLASSNAME = "s-group-btn";
	
	public String getTemplate(){
		return DEFAULT_TEMPLATES;
	}
	
	protected String getDefaultClass(XMap view,SparkContext context){
		return DEFAULT_CLASSNAME;
	}
	
	public String execute(XMap view, SparkContext context) throws Exception {
		super.init(view, context);
		List<XMap> children = view.getChilds();
		StringBuilder sb = new StringBuilder();
		if (children != null) {
			String style = (String)context.get(PROPERTITY_STYLE);
			sb.append("<table class=\"s-group-btn\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\"");
			if(style != null){
				sb.append(" style=\"").append(style).append("\"");
			}
			sb.append("><tr>");
			int i = 1,len = children.size();
			for (XMap item : children) {
				String cls = item.getString(Button.PROPERTITY_CLASSNAME, "");
				if(i==1){
					item.put(Button.PROPERTITY_CLASSNAME, cls + " f");
				}else if(i==len){
					item.put(Button.PROPERTITY_CLASSNAME, cls + " l");	
				}else {
					item.put(Button.PROPERTITY_CLASSNAME, cls + " m");
				}
				sb.append("<td>");
				sb.append(SparkBuilder.build(item, context));
				sb.append("</td>");
				i++;
			}
			sb.append("</table>");
//			context.put(PROPERTITY_BUTTONS, sb.toString());
		}
		return sb.toString();
	}
	
	@SuppressWarnings("unchecked")
	protected String build(SparkContext context){
		Map map = context.getMap();
		StringBuilder sb = new StringBuilder();
		sb.append("<div class=\"").append(get(map,"className")).append("\" style=\"").append(get(map,"style")).append(";\">\r");
		sb.append("    ").append(get(map,"buttons"));
		sb.append("</div>\r");
		return sb.toString();
	}
}
